package com.chenlei.toppopup;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chenlei.toppopup.adapter.CLBasePopupAdapter;
import com.chenlei.toppopup.adapter.CLTopPopupAdapter;
import com.chenlei.toppopup.layoutmanager.CustomLinearLayoutManager;
import com.chenlei.toppopup.model.CLModel;
import com.chenlei.toppopup.util.UnitUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenlei on 2017/12/12.
 */

public class CLTopPopup extends PopupWindow implements CLBasePopupAdapter.OnItemClickListener, View.OnTouchListener {
  public static final int TOPPOPUP_ONE = 0x11;//单列选择
  public static final int TOPPOPUP_TWO = 0x12;//双列选择

  private Context mContext;
  private Builder mBuilder;
  private View mTopView;

  private View mMenuView;
  private RecyclerView mLeftRecyclerView;
  private RecyclerView mRightRecyclerView;
  private View bgLine;
  private View bottomLine;
  private LinearLayout bottomView;
  private TextView bottomLeftBtn;
  private TextView bottomRightBtn;

  private CLTopPopupAdapter leftAdapter;
  private CLTopPopupAdapter rightAdapter;
  private OnItemClickListener onItemClickListener;
  private OnDismissListener onDismissListener;

  private int leftPos;
  private String inputText;
  /**
   * @param context        Context
   * @param topView        上视图  在他下面创建
   * @param builder        配置
   */
  public CLTopPopup(Context context,View topView,Builder builder)
  {
    mContext = context;
    mBuilder = builder;
    mTopView = topView;

    //初始化界面

    mMenuView = LayoutInflater.from(mContext).inflate(R.layout.cl_toppopup_layout, null);

    initWidget();
    setPop();

    initAdapter();
  }

  //初始化控件
  private void initWidget()
  {
    mLeftRecyclerView = (RecyclerView) mMenuView.findViewById(R.id.cl_toppopup_left_recycler);
    mRightRecyclerView = (RecyclerView) mMenuView.findViewById(R.id.cl_toppopup_right_recycler);

    bgLine = (View) mMenuView.findViewById(R.id.cl_toppopup_bgline_view);
    bottomLine = (View) mMenuView.findViewById(R.id.cl_toppopup_line_view);

    bottomView = (LinearLayout) mMenuView.findViewById(R.id.cl_toppopup_bottom_view);

    bottomLeftBtn = (TextView) mMenuView.findViewById(R.id.cl_toppopup_bottom_view_left_btn);
    bottomRightBtn = (TextView) mMenuView.findViewById(R.id.cl_toppopup_bottom_view_right_btn);
  }

  private void setPop()
  {
    // 设置AccessoryPopup的view
    this.setContentView(mMenuView);

    this.setBackgroundDrawable(ContextCompat.getDrawable(mContext,android.R.color.transparent));

    // 设置AccessoryPopup弹出窗体的宽度
    this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

    if (mBuilder.getType() == TOPPOPUP_ONE)
      mLeftRecyclerView.setVisibility(View.GONE);

    // 设置AccessoryPopup弹出窗体的高度 如果设置了高度百分比则按高度百分比计算 否则-是单列  则动态高度 双列则为屏幕1/2
    if (mBuilder.getType() == TOPPOPUP_ONE && mBuilder.getHeightPer() <= 0){
      this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }else{
      float heightPer = mBuilder.getHeightPer();
      if (mBuilder.getHeightPer() <= 0)
        heightPer = 0.5f;
      DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
      int height = metrics.heightPixels;
      this.setHeight((int) (height * heightPer));
    }

    // 设置AccessoryPopup弹出窗体可点击
    this.setFocusable(true);

    //获取回调
    onItemClickListener = mBuilder.getItemClickListener();
    onDismissListener = mBuilder.getOnDismissListener();

    // 实例化一个ColorDrawable颜色为半透明 默认为#f2f2f2
    ColorDrawable dw;
    if (mBuilder.getBgColor() == 0)
      dw = new ColorDrawable(Color.parseColor("#f2f2f2"));
    else
      dw = new ColorDrawable(ContextCompat.getColor(mContext,mBuilder.getBgColor()));
    // 设置SelectPicPopupWindow弹出窗体的背景
    this.setBackgroundDrawable(dw);

    // 设置线的颜色及显示情况
    if (!mBuilder.isShowLine())
    {
      // 不显示分割线
      bgLine.setVisibility(View.GONE);
      bottomLine.setVisibility(View.GONE);
    }
    else
    {
      // 显示分割线
      bottomLine.setVisibility(View.VISIBLE);
      int lineColor = Color.parseColor("#f2f2f2");
      if (mBuilder.getLineColor() != 0)
        lineColor = ContextCompat.getColor(mContext,mBuilder.getLineColor());
      bottomLine.setBackgroundColor(lineColor);
      if (mBuilder.getType() == TOPPOPUP_ONE)
      {
        bgLine.setVisibility(View.GONE);
      }
      else
      {
        bgLine.setVisibility(View.VISIBLE);
        bgLine.setBackgroundColor(lineColor);
      }
    }

    //设置左侧列表背景
    int leftBgColor = Color.parseColor("#ffffff");
    if (mBuilder.getLeftBgColor() != 0)
      leftBgColor = ContextCompat.getColor(mContext,mBuilder.getLeftBgColor());
    mLeftRecyclerView.setBackgroundColor(leftBgColor);

    //设置右侧列表背景
    int rightBgColor = Color.parseColor("#ffffff");
    if (mBuilder.getRightBgColor() != 0)
      rightBgColor = ContextCompat.getColor(mContext,mBuilder.getRightBgColor());
    mRightRecyclerView.setBackgroundColor(rightBgColor);

    //设置左侧列表比例
    float leftPer = 1-mBuilder.getRightPer();
    LinearLayout.LayoutParams layoutParamsLeft = (LinearLayout.LayoutParams)mLeftRecyclerView.getLayoutParams();
    layoutParamsLeft.weight = leftPer;
    mLeftRecyclerView.setLayoutParams(layoutParamsLeft);

    //设置右侧列表比例
    LinearLayout.LayoutParams layoutParamsRight = (LinearLayout.LayoutParams)mRightRecyclerView.getLayoutParams();
    layoutParamsRight.weight = mBuilder.getRightPer();
    mRightRecyclerView.setLayoutParams(layoutParamsRight);

    if (mBuilder.isShowBottomView()){
      bottomView.setVisibility(View.VISIBLE);
      bottomLeftBtn.setText(mBuilder.getBottomViewBuilder().getLeftText());
      bottomRightBtn.setText(mBuilder.getBottomViewBuilder().getRightText());

      int leftBtnBgColor = Color.parseColor("#ffffff");
      if (mBuilder.getBottomViewBuilder().getLeftBtnColor() != 0)
        leftBtnBgColor = ContextCompat.getColor(mContext,mBuilder.getBottomViewBuilder().getLeftBtnColor());
      bottomLeftBtn.setBackgroundColor(leftBtnBgColor);

      int rightBtnBgColor = Color.parseColor("#ffffff");
      if (mBuilder.getBottomViewBuilder().getRightBtnColor() != 0)
        rightBtnBgColor = ContextCompat.getColor(mContext,mBuilder.getBottomViewBuilder().getRightBtnColor());
      bottomRightBtn.setBackgroundColor(rightBtnBgColor);

      int leftBtnTextColor = Color.parseColor("#000000");
      if (mBuilder.getBottomViewBuilder().getLeftBtnTextColor() != 0)
        leftBtnTextColor = ContextCompat.getColor(mContext,mBuilder.getBottomViewBuilder().getLeftBtnTextColor());
      bottomLeftBtn.setTextColor(leftBtnTextColor);

      int rightBtnTextColor = Color.parseColor("#000000");
      if (mBuilder.getBottomViewBuilder().getRightBtnTextColor() != 0)
        rightBtnTextColor = ContextCompat.getColor(mContext,mBuilder.getBottomViewBuilder().getRightBtnTextColor());
      bottomRightBtn.setTextColor(rightBtnTextColor);

      bottomLeftBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, UnitUtils.sp2px(mContext,mBuilder.getBottomViewBuilder().getLeftTextSize()));
      bottomRightBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, UnitUtils.sp2px(mContext,mBuilder.getBottomViewBuilder().getRightTextSize()));

      bottomLeftBtn.setOnTouchListener(this);
      bottomRightBtn.setOnTouchListener(this);

      LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) bottomView.getLayoutParams();
      layoutParams.height = UnitUtils.dip2px(mContext,mBuilder.getBottomViewBuilder().getHeight());
      bottomView.setLayoutParams(layoutParams);
    }else{
      bottomView.setVisibility(View.GONE);
    }

    // 设置AccessoryPopup弹出窗体的动画效果
    //this.setAnimationStyle(R.style.AnimTopMiddle);
  }

  private void initAdapter(){
    rightAdapter = new CLTopPopupAdapter(mContext, mBuilder.getRightTextBuilder(),
            new ArrayList<CLModel>(),0);
    rightAdapter.setOnItemClickListener(this);
    mRightRecyclerView.setLayoutManager(new CustomLinearLayoutManager(mContext));
    mRightRecyclerView.setAdapter(rightAdapter);

    ArrayList<CLModel> arrayList = new ArrayList<>();
    if (mBuilder.getLeftEndTextBuilder() != null) {
      CLModel clModel = new CLModel();
      clModel.setText(mBuilder.getLeftEndTextBuilder().getText());
      arrayList.add(clModel);
    }

    if (mBuilder.getType() == TOPPOPUP_TWO)
    {
      leftAdapter = new CLTopPopupAdapter(mContext, mBuilder.getLeftTextBuilder(), mBuilder.getLeftEndTextBuilder(), arrayList, 0);
      leftAdapter.setOnItemClickListener(new CLBasePopupAdapter.OnItemClickListener()
      {
        @Override
        public void onItemClick(int pos)
        {
          leftPos = pos;
          if (onItemClickListener != null)
          {
            if (mBuilder.getLeftEndTextBuilder() != null && leftPos == leftAdapter.getItemCount()-1)
            {
              onItemClickListener.onLeftEndItemClick();
              dismiss();
            }
            else
            {
              onItemClickListener.onLeftItemClick(leftPos);
            }
          }
        }

        @Override
        public void onItemInputText(String text) {
        }
      });
      mLeftRecyclerView.setLayoutManager(new CustomLinearLayoutManager(mContext));
      mLeftRecyclerView.setAdapter(leftAdapter);
    }
  }

  public void setLeftData(List<CLModel> leftData,int selectIndex){
    leftPos = selectIndex;
    leftAdapter.setSelectIndex(selectIndex);
    ArrayList<CLModel> arrayList = new ArrayList<>();
    arrayList.addAll(leftData);
    if (mBuilder.getLeftEndTextBuilder() != null) {
      CLModel clModel = new CLModel();
      clModel.setText(mBuilder.getLeftEndTextBuilder().getText());
      arrayList.add(clModel);
    }
    leftAdapter.updateAdapterClearBeforeDatas(arrayList);
  }

  public void setRightData(List<CLModel> rightData,int selectIndex){
    rightAdapter.setSelectIndex(selectIndex);
    rightAdapter.updateAdapterClearBeforeDatas(rightData);
  }

  @Override
  public void onItemClick(int pos)
  {
    if (onItemClickListener != null)
      onItemClickListener.onRightItemClick(leftPos,pos);
    if (!mBuilder.isShowBottomView())
      dismiss();
  }

  @Override
  public void onItemInputText(String text) {
    inputText = text;
  }

  public void show(){
    showAsDropDown(mTopView, 0, 0);
    if (mBuilder.getItemClickListener() != null)
      mBuilder.getItemClickListener().onLeftItemClick(leftPos);
  }

  @Override
  public void dismiss()
  {
    if (onDismissListener != null)
      onDismissListener.onTopPopupDismiss();
    super.dismiss();
  }

  @Override
  public boolean onTouch(View view, MotionEvent motionEvent) {
    if (view == bottomLeftBtn){
      if (onItemClickListener != null)
        onItemClickListener.onBottomLeftItemClick();
    }else if (view == bottomRightBtn){
      if (onItemClickListener != null)
        onItemClickListener.onBottomRightItemClick();
    }
    return false;
  }

  public String getInputText() {
    return inputText;
  }

  public interface OnItemClickListener{
    void onLeftItemClick(int pos);
    void onRightItemClick(int leftPos,int rightPos);
    void onLeftEndItemClick();

    void onBottomLeftItemClick();
    void onBottomRightItemClick();
  }

  public interface OnDismissListener{
    void onTopPopupDismiss();
  }

  public static class TextBuilder{
    private int textSize = 16;//文字大小

    private @ColorRes int normalTextColor = 0;//默认文字颜色
    private @ColorRes int selectTextColor = 0;//选中文字颜色

    private @ColorRes int normalBgColor = 0;//默认背景颜色
    private @ColorRes int selectBgColor = 0;//选中背景颜色

    //左侧不存在
    private @DrawableRes int normalDrawable = 0;//默认选中图片
    private @DrawableRes int selectDrawable = 0;//选中状态图片

    private int height = 44;//单行高度  dp

    private boolean showLine = false;//是否显示间隔线
    private int lineMarginStart = 0;//间隔线左边距
    private int lineMarginEnd = 0;//间隔线右边距
    private @ColorRes int lineColor = 0;//间隔线颜色

    private boolean textLeft = true;
    private int textMarginStart = 16;//文本左边距
    private int textMarginEnd = 16;//文本右边距

    public int getTextSize()
    {
      return textSize;
    }

    public TextBuilder setTextSize(int textSize)
    {
      this.textSize = textSize;
      return this;
    }

    public int getNormalTextColor()
    {
      return normalTextColor;
    }

    public TextBuilder setNormalTextColor(int normalTextColor)
    {
      this.normalTextColor = normalTextColor;
      return this;
    }

    public int getSelectTextColor()
    {
      return selectTextColor;
    }

    public TextBuilder setSelectTextColor(int selectTextColor)
    {
      this.selectTextColor = selectTextColor;
      return this;
    }

    public int getNormalBgColor()
    {
      return normalBgColor;
    }

    public TextBuilder setNormalBgColor(int normalBgColor)
    {
      this.normalBgColor = normalBgColor;
      return this;
    }

    public int getSelectBgColor()
    {
      return selectBgColor;
    }

    public TextBuilder setSelectBgColor(int selectBgColor)
    {
      this.selectBgColor = selectBgColor;
      return this;
    }

    public int getNormalDrawable()
    {
      return normalDrawable;
    }

    public TextBuilder setNormalDrawable(int normalDrawable)
    {
      this.normalDrawable = normalDrawable;
      return this;
    }

    public int getSelectDrawable()
    {
      return selectDrawable;
    }

    public TextBuilder setSelectDrawable(int selectDrawable)
    {
      this.selectDrawable = selectDrawable;
      return this;
    }

    public int getHeight()
    {
      return height;
    }

    public TextBuilder setHeight(int height)
    {
      this.height = height;
      return this;
    }

    public boolean isShowLine()
    {
      return showLine;
    }

    public TextBuilder setShowLine(boolean showLine)
    {
      this.showLine = showLine;
      return this;
    }

    public int getLineMarginStart()
    {
      return lineMarginStart;
    }

    public TextBuilder setLineMarginStart(int lineMarginStart)
    {
      this.lineMarginStart = lineMarginStart;
      return this;
    }

    public int getLineMarginEnd()
    {
      return lineMarginEnd;
    }

    public TextBuilder setLineMarginEnd(int lineMarginEnd)
    {
      this.lineMarginEnd = lineMarginEnd;
      return this;
    }

    public int getLineColor()
    {
      return lineColor;
    }

    public TextBuilder setLineColor(int lineColor)
    {
      this.lineColor = lineColor;
      return this;
    }

    public boolean isTextLeft()
    {
      return textLeft;
    }

    public TextBuilder setTextLeft(boolean textLeft)
    {
      this.textLeft = textLeft;
      return this;
    }

    public int getTextMarginStart()
    {
      return textMarginStart;
    }

    public TextBuilder setTextMarginStart(int textMarginStart)
    {
      this.textMarginStart = textMarginStart;
      return this;
    }

    public int getTextMarginEnd()
    {
      return textMarginEnd;
    }

    public TextBuilder setTextMarginEnd(int textMarginEnd)
    {
      this.textMarginEnd = textMarginEnd;
      return this;
    }
  }

  public static class LeftEndTextBuilder{
    private String text = "添加";//文本
    private @ColorRes int textColor = 0;//文本颜色
    private int textSize = 16;//文本大小

    private int height = 44;//单行高度

    public String getText()
    {
      return text;
    }

    public LeftEndTextBuilder setText(String text)
    {
      this.text = text;
      return this;
    }

    public int getTextColor()
    {
      return textColor;
    }

    public LeftEndTextBuilder setTextColor(int textColor)
    {
      this.textColor = textColor;
      return this;
    }

    public int getTextSize()
    {
      return textSize;
    }

    public LeftEndTextBuilder setTextSize(int textSize)
    {
      this.textSize = textSize;
      return this;
    }

    public int getHeight()
    {
      return height;
    }

    public LeftEndTextBuilder setHeight(int height)
    {
      this.height = height;
      return this;
    }
  }

  public static class BottomViewBuilder{
    private @ColorRes int leftBtnColor = 0;//左侧按钮颜色 默认#ffffff
    private @ColorRes int rightBtnColor = 0;//右侧按钮颜色 默认#ffffff
    private @ColorRes int leftBtnTextColor = 0;//左侧按钮字体颜色  默认#000000
    private @ColorRes int rightBtnTextColor = 0;//右侧按钮字体颜色 默认#000000

    private int leftTextSize = 16;//左侧文字大小
    private int rightTextSize = 16;//右侧文字大小

    private int height = 44;//底部视图高度  dp

    private String leftText;//左侧文本
    private String rightText;//右侧文本

    public int getLeftBtnColor() {
      return leftBtnColor;
    }

    public BottomViewBuilder setLeftBtnColor(int leftBtnColor) {
      this.leftBtnColor = leftBtnColor;
      return this;
    }

    public int getRightBtnColor() {
      return rightBtnColor;
    }

    public BottomViewBuilder setRightBtnColor(int rightBtnColor) {
      this.rightBtnColor = rightBtnColor;
      return this;
    }

    public int getLeftBtnTextColor() {
      return leftBtnTextColor;
    }

    public BottomViewBuilder setLeftBtnTextColor(int leftBtnTextColor) {
      this.leftBtnTextColor = leftBtnTextColor;
      return this;
    }

    public int getRightBtnTextColor() {
      return rightBtnTextColor;
    }

    public BottomViewBuilder setRightBtnTextColor(int rightBtnTextColor) {
      this.rightBtnTextColor = rightBtnTextColor;
      return this;
    }

    public int getHeight() {
      return height;
    }

    public BottomViewBuilder setHeight(int height) {
      this.height = height;
      return this;
    }

    public String getLeftText() {
      return leftText;
    }

    public BottomViewBuilder setLeftText(String leftText) {
      this.leftText = leftText;
      return this;
    }

    public String getRightText() {
      return rightText;
    }

    public BottomViewBuilder setRightText(String rightText) {
      this.rightText = rightText;
      return this;
    }

    public int getLeftTextSize() {
      return leftTextSize;
    }

    public BottomViewBuilder setLeftTextSize(int leftTextSize) {
      this.leftTextSize = leftTextSize;
      return this;
    }

    public int getRightTextSize() {
      return rightTextSize;
    }

    public BottomViewBuilder setRightTextSize(int rightTextSize) {
      this.rightTextSize = rightTextSize;
      return this;
    }
  }

  public static class Builder{
    private int type = TOPPOPUP_ONE;//样式   单列  双列

    private float rightPer = 0.5f;//右侧百分比

    private @ColorRes int lineColor = 0;//线颜色   默认颜色为#f2f2f2

    private boolean showLine = true;//是否显示分割线

    private boolean showBottomView = false;//是否显示下布局

    private float heightPer = 0;//弹出框高度百分比

    private @ColorRes int bgColor = 0;//背景框颜色   默认颜色为#f2f2f2
    private @ColorRes int leftBgColor = 0;//左侧列表背景  默认#ffffff
    private @ColorRes int rightBgColor = 0;//右侧列表背景  默认#ffffff

    private TextBuilder leftTextBuilder = new TextBuilder();//左侧文本样式
    private TextBuilder rightTextBuilder = new TextBuilder();//右侧文本样式

    private LeftEndTextBuilder leftEndTextBuilder;//左侧最后一个自定义  默认无

    private BottomViewBuilder bottomViewBuilder = new BottomViewBuilder();//底部布局定义  默认无

    private CLTopPopup.OnItemClickListener  onItemClickListener;

    private CLTopPopup.OnDismissListener onDismissListener;

    public int getType()
    {
      return type;
    }

    public Builder setType(int type)
    {
      this.type = type;
      return this;
    }

    public float getRightPer()
    {
      return rightPer;
    }

    public Builder setRightPer(float rightPer)
    {
      this.rightPer = rightPer;
      return this;
    }

    public int getLineColor()
    {
      return lineColor;
    }

    public Builder setLineColor(int lineColor)
    {
      this.lineColor = lineColor;
      return this;
    }

    public boolean isShowLine()
    {
      return showLine;
    }

    public Builder setShowLine(boolean showLine)
    {
      this.showLine = showLine;
      return this;
    }

    public boolean isShowBottomView() {
      return showBottomView;
    }

    public Builder setShowBottomView(boolean showBottomView) {
      this.showBottomView = showBottomView;
      return this;
    }

    public float getHeightPer()
    {
      return heightPer;
    }

    public Builder setHeightPer(float heightPer)
    {
      this.heightPer = heightPer;
      return this;
    }

    public int getBgColor()
    {
      return bgColor;
    }

    public Builder setBgColor(int bgColor)
    {
      this.bgColor = bgColor;
      return this;
    }

    public int getLeftBgColor()
    {
      return leftBgColor;
    }

    public Builder setLeftBgColor(int leftBgColor)
    {
      this.leftBgColor = leftBgColor;
      return this;
    }

    public int getRightBgColor()
    {
      return rightBgColor;
    }

    public Builder setRightBgColor(int rightBgColor)
    {
      this.rightBgColor = rightBgColor;
      return this;
    }

    public TextBuilder getLeftTextBuilder()
    {
      return leftTextBuilder;
    }

    public Builder setLeftTextBuilder(TextBuilder leftTextBuilder)
    {
      this.leftTextBuilder = leftTextBuilder;
      return this;
    }

    public TextBuilder getRightTextBuilder()
    {
      return rightTextBuilder;
    }

    public Builder setRightTextBuilder(TextBuilder rightTextBuilder)
    {
      this.rightTextBuilder = rightTextBuilder;
      return this;
    }

    public LeftEndTextBuilder getLeftEndTextBuilder()
    {
      return leftEndTextBuilder;
    }

    public Builder setLeftEndTextBuilder(LeftEndTextBuilder leftEndTextBuilder)
    {
      this.leftEndTextBuilder = leftEndTextBuilder;
      return this;
    }

    public CLTopPopup.OnItemClickListener  getItemClickListener()
    {
      return onItemClickListener;
    }

    public Builder setItemClickListener(CLTopPopup.OnItemClickListener onItemClickListener)
    {
      this.onItemClickListener = onItemClickListener;
      return this;
    }

    public BottomViewBuilder getBottomViewBuilder() {
      return bottomViewBuilder;
    }

    public Builder setBottomViewBuilder(BottomViewBuilder bottomViewBuilder) {
      this.bottomViewBuilder = bottomViewBuilder;
      return this;
    }

    public OnDismissListener getOnDismissListener()
    {
      return onDismissListener;
    }

    public Builder setOnDismissListener(CLTopPopup.OnDismissListener onDismissListener)
    {
      this.onDismissListener = onDismissListener;
      return this;
    }
  }
}
